package net.crahtoot.pisasa.web;

import java.util.ArrayList;
import java.util.List;

import net.crahtoot.pisasa.domain.Account;
import net.crahtoot.pisasa.domain.picasa.Album;
import net.crahtoot.pisasa.service.PhotoService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import flexjson.JSONSerializer;

@Controller
@RequestMapping("/albumRest")
public class AlbumRestController {
    private static final Log log = LogFactory.getLog(AlbumRestController.class);

    @Autowired
    private PhotoService photoService;

    public static String toJson(final Object bean) {
        return new JSONSerializer().exclude("*.class").serialize(bean);
    }

    /**
     * @return tous les albums de tous les utilisateurs.
     * @throws Exception
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<Album> listAlbums() throws Exception {
        final List<Account> accounts = Account.findAllAccounts();

        if (accounts == null || accounts.size() == 0) {
            return null;
        }

        final List<Album> albums = new ArrayList<Album>();
        for (final Account account : accounts) {
            albums.addAll(photoService.getAlbums(account));
        }
        log.debug(albums.size() + " album(s) pour " + accounts.size() + " utilisateur(s).");

        return albums;
    }

    /**
     * @param userId : username
     * @return les albums de l'utilisateur
     * @throws Exception
     */
    @RequestMapping(value = "/{userId:.*}/")
    public List<Album> listAllAlbums(@PathVariable final String userId) throws Exception {
        final Account account = (Account) Account.findAccountsByUsernameEquals(userId).getSingleResult();
        if (account == null) {
            return null;
        }
        final List<Album> albums = photoService.getAlbums(account);

        return albums;
    }
}
